<script setup>
import NavigationBarStricky from "@/views/Common/NavigationBarSticky.vue";
import PageHeader from "@/views/Common/PageHeader.vue";
import NavigationBar from "@/views/Common/NavigationBar.vue";
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import {Delete, Plus} from "@element-plus/icons-vue";
import http from "@/utils/http.js";
import { useUserStore } from "@/stores/user";
import { useRouter } from "vue-router";

// 修改表单数据结构
const userStore = useUserStore();
const router = useRouter();

const articleForm = ref({
  title: '',
  category: '',
  content: '',
  expert_id: userStore?.userInfo?.uid || '', // 从登录态获取专家ID
  imageFiles: [] // 统一存储所有图片文件
});

// 文章分类选项
const categories = ref([
  { value: '1', label: '种植技术' },
  { value: '2', label: '病虫害防治' },
  { value: '3', label: '农业政策' },
  { value: '4', label: '市场行情' },
  { value: '5', label: '农业科技' }
]);

// 处理图片上传
const handleImageUpload = (file) => {
  const imageUrl = URL.createObjectURL(file);
  articleForm.value.imageFiles.push({
    url: imageUrl,
    raw: file
  });
  return false;
};

// 删除图片
const deleteImage = (index) => {
  articleForm.value.imageFiles.splice(index, 1);
  ElMessage.success('图片已删除');
};

// 提交文章
const submitArticle = async () => {
  try {
    // 表单验证
    if (!articleForm.value.title.trim()) {
      ElMessage.error('请输入文章标题');
      return;
    }
    if (!articleForm.value.category) {
      ElMessage.error('请选择文章分类');
      return;
    }
    if (!articleForm.value.content.trim()) {
      ElMessage.error('请输入文章内容');
      return;
    }
    if (articleForm.value.imageFiles.length === 0) {
      ElMessage.error('请至少上传一张图片');
      return;
    }

    // 处理文章内容，在需要插入图片的段落后添加特殊标记
    const formattedContent = articleForm.value.content
      .split('\n')
      .map(para => para.trim())
      .filter(para => para.length > 0)
      .map((para, index) => {
        // 假设用户在段落后加入 [图片1] 这样的标记来指定图片位置
        return para.replace(/\[图片(\d+)\]/g, '{{image_$1}}');
      })
      .join('\n');

    // 准备表单数据
    const formData = new FormData();
    const articleData = {
      title: articleForm.value.title,
      category: articleForm.value.category,
      content: formattedContent,
      expert_id: articleForm.value.expert_id,
    };
    formData.append('article', new Blob([JSON.stringify(articleData)], { type: 'application/json' }));

    // 添加所有图片文件
    articleForm.value.imageFiles.forEach(file => {
      formData.append('files', file.raw);
    });

    // 发送请求
    const response = await http.post('/expert/article', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    if (response.code === 200) {
      ElMessage.success('文章发布成功');
      // 跳转到文章详情页
      const aid = response.data?.article_id;
      if (aid) {
        router.push(`/expert/articleDetail/${aid}`);
      } else {
        // 若未返回ID，则回退为重置表单
        articleForm.value = {
          title: '',
          category: '',
          content: '',
          expert_id: userStore?.userInfo?.uid || '',
          imageFiles: []
        };
      }
    } else {
      ElMessage.error(response.message || '发布失败');
    }
  } catch (error) {
    console.error('发布文章失败:', error);
    ElMessage.error('发布失败：' + error.message);
  }
};
</script>

<template>
  <div class="article-page">
    <div class="header-white">
      <NavigationBarStricky />
      <PageHeader />
      <navigation-bar></navigation-bar>
    </div>


    <div class="content-wrapper">
      <div class="article-form">
        <h2 class="form-title">发布农技学堂科普文章</h2>

        <el-form :model="articleForm" label-width="100px">
          <el-form-item label="文章标题">
            <el-input v-model="articleForm.title" placeholder="请输入文章标题"/>
          </el-form-item>

          <el-form-item label="文章分类">
            <el-select v-model="articleForm.category" placeholder="请选择文章分类">
              <el-option 
                v-for="item in categories" 
                :key="item.value" 
                :label="item.label" 
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="文章内容">
            <el-input
              v-model="articleForm.content"
              type="textarea"
              :rows="15"
              placeholder="请输入文章内容，在需要插入图片的段落后添加[图片1]、[图片2]等标记"
            />
            <div class="content-tips">
              <p style="color: red">文章编写提示：</p>
              <ul>
                <li>每个段落之间请按<b>回车键</b>空一行</li>
                <li>在需要插入图片的段落后添加[图片1]、[图片2]等标记</li>
                <li>图片序号需要与上传的图片顺序对应</li>
                <li>例如：这是第一段内容。<b>[图片1]</b></li>
              </ul>
            </div>
          </el-form-item>

          <el-form-item label="上传图片">
            <el-upload
                action="#"
                :show-file-list="false"
                :before-upload="handleImageUpload"
                class="image-uploader">
              <el-button type="primary">
                <el-icon><Plus /></el-icon>
                添加图片
              </el-button>
            </el-upload>
            <div class="upload-tip">第一张图片将作为封面图片显示</div>
          </el-form-item>

          <!-- 图片预览区域 -->
          <el-form-item v-if="articleForm.imageFiles.length" label="已上传图片">
            <div class="image-preview-list">
              <div v-for="(img, index) in articleForm.imageFiles" 
                   :key="index" 
                   class="image-preview-item">
                <img :src="img.url" :alt="`图片${index + 1}`">
                <div class="image-label">
                  {{ index === 0 ? '封面图片' : `内容图片${index + 1}` }}
                </div>
                <div class="delete-mask" @click="deleteImage(index)">
                  <el-icon class="delete-icon"><Delete /></el-icon>
                </div>
              </div>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitArticle">发布文章</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.article-page {
  min-height: 100vh;
  background-color: #f3f6f8;
}

.content-wrapper {
  max-width: 1160px;
  margin: 0 auto;
  padding: 20px 0 40px;
}

.article-form {
  background-color: white;
  border-radius: 10px;
  padding: 32px;
  box-shadow: 0 0 5px 0 rgba(144,144,144,0.29);

  .form-title {
    text-align: center;
    margin-bottom: 20px;
    font-size: 22px;
    font-weight: 600;
    color: #333;
  }
}

:deep(.el-form-item) {
  display: flex;
  justify-content: center;
  
  .el-form-item__content {
    max-width: 800px;
    flex: 1;
  }
}

.image-preview-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;

  .image-preview-item {
    position: relative;
    width: 200px;

    img {
      width: 100%;
      height: 150px;
      object-fit: cover;
      border-radius: 8px;
    }

    .image-label {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, 0.6);
      color: white;
      padding: 4px;
      text-align: center;
    }

    .delete-mask {
      display: none;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      justify-content: center;
      align-items: center;
      cursor: pointer;
      border-radius: 8px;

      &:hover {
        display: flex;
      }
    }

    &:hover .delete-mask {
      display: flex;
    }
  }
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

:deep(.el-button--primary){
  background-color: #409eff; /* 保持默认主题色，如需强一致可换为 #39bf3e */
  border-color: #409eff;
}
.header-white{
  background-color: #fff;
  width: 100%;
}

</style>